<template>
 <!-- 所有身份的登录页面 -->
 <div class="container">
      <div class="login-weaper">
            <!-- 左边 -->
            <div class="login-left">
              <p class="title">社区养老服务管理系统</p>
            </div>
            <!-- 右边 -->
            <div class="login-right">
               <el-form :model="form" :rules="rules">
                  <div style="display: flex;">
                    <img src="../assets/logo.png" alt="标志" style="height: 30px;width: 30px;padding: 7px 20px 0px 100px; ">
                    <div class="title-right">欢迎使用!</div>
                  </div>
                  <el-form-item 
                    prop="phone">
                    <el-input 
                      v-model="form.phone"
                      placeholder="请输入手机号~"
                      prefix-icon="el-icon-user"
                      >
                    </el-input>
                  </el-form-item>

                  <el-form-item 
                    prop="password">
                    <el-input 
                      :type="isPass" 
                      v-model="form.password"
                      placeholder="请输入密码~"
                      prefix-icon="el-icon-lock"
                      >
                      <i slot="suffix" class="el-icon-view" @click="apperPassWord"></i>
                    </el-input>
                  </el-form-item>

                  <!-- 验证码 -->
                  <div class="status">
                    <div style="display: flex;justify-content: center;">
                      <el-form-item prop="inputYZM" style="width: 100%;">
                        <el-input v-model="form.inputYZM" prefix-icon="el-icon-lock"  placeholder="请输入验证码"></el-input>
                      </el-form-item>
                      <canvas @click="updateYZM" id="canvas" slot="append" width="150px" height="40pxpx" style="height: 40px;margin-left: -2px;"></canvas>
                    </div>
                  </div>

                  <el-form-item>
                    <el-button 
                      type="success" 
                      @click="onSubmit"
                      :loading="loading"         
                      >
                      登录
                    </el-button>
                  </el-form-item>
               </el-form>
            </div>
      </div>
  </div>
</template>

<script>
  import axios from 'axios';
  // 避免传json格式的对象给服务器
  import Qs from 'qs'
  export default {
    name: 'Login',
    data() {
      return {
        // 用户名和密码的校验规则
        rules:{
          phone:[{required: true, message: '请输入手机号', trigger: 'blur' }],
          password:[{required: true, message: '请输入密码', trigger: 'blur' }],
          inputYZM:[{required: true, message: '请输入验证码', trigger: 'blur' }]
        },
        // 表单数据收集
        form: {
          phone: '',
          password:'',
          inputYZM:''
        },
        loading:false,     // 控制按钮是否显示"加载中"
        isPass:'password', // 控制是否显示密码
        yzm:'',
        
      }
    },
    methods: {
      updateYZM(){
        this.yzm = this.captcha('#canvas',150,40);
      },
      // 收集form表单数据
      onSubmit() {

        // 1.检测用户输入是否合法
        if(this.form.phone.trim() === "" || this.form.password.trim() === "" ||
           this.form.phone.length !== 11 || this.form.password.length < 6
        ){
            this.$message({
              message: '请输入正确的手机号或密码!',
              type: 'warning'
            });
          this.form.phone = '';
          this.form.password = '';
          return;
        }

        // 2.检查验证码
        if(this.form.inputYZM.toLowerCase() !== this.yzm.toLowerCase()){
          this.$message({
              message: '请输入正确的验证码!',
              type: 'warning'
            });
          this.yzm = this.captcha('#canvas',150,40);
          this.form.inputYZM = '';
          return;
        }

        // 显示按钮动画
        this.loading = true;

        // 发送请求,使用户登录
        axios.post('http://localhost:8088/home/login',Qs.stringify(this.form)).then(
          response => {
            if(response.data.result === "success"){
                // 提示一下登录成功
                this.$message({
                  message: '登录成功!',
                  type: 'success'
                });
                // 将用户数据存放到本次回话中
                sessionStorage.setItem('user',JSON.stringify(response.data.data.user));
                // 放token
                localStorage.setItem('token',response.data.data.token);
                // 延时显示一下成功提示
                if(response.data.data.user.status === '超级管理员' || response.data.data.user.status === '员工'){
                        // 表示登录成功,切换路由到首页
                        this.$router.push({path:'/home'})
                }
                if(response.data.data.user.status === '老人'){
                        // 表示登录成功,切换到前台页面
                        this.$router.push({path:'/index'})
                }

            }else{
              // 提示一下用户名或密码错误
              this.$message.error(response.data.msg);
              this.loading = false;           // 关闭按钮动画
            }
          },
          error => {
              if(error.response.status === 701){
                  window.location.replace('http://localhost:8080/');
              }else{
                  //错误信息打印到控制台 
                  console.log(error.message);
                  this.loading = false;           // 关闭按钮动画
              }
          }
        );
      },
      // 显示密码
      apperPassWord(){
        this.isPass = this.isPass === 'password'?'':'password';
      },

      captcha(canva,width,height){
        // 生成一个随机数
        function randomNumber(min,max){
            return parseInt(Math.random()*(max-min)+min);
        }

        // 随机生成颜色(带透明度)
        function randomColor(min,max){
            let r = randomNumber(min,max);
            let g = randomNumber(min,max);
            let b = randomNumber(min,max);
            let a = Math.random()*0.3+0.3;
            return "rgba("+r+","+g+","+b+","+a+")";
        }

        let canvas = document.querySelector(canva);
        //拿到2d画笔
        let print = canvas.getContext('2d');
        // 清空画板
        print.clearRect(0,0,150,40);
        //绘制背景颜色
        print.fillStyle = randomColor(130,200);
        print.fillRect(0,0,width,height);

        //随机字符串
        let str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890abcdefghijklmnopqrstuvwxyz";

        //存放每次随机的值
        let result = "";
        for(let i = 0; i < 4; i++){
            //随机的每个字符
            let ch = str[randomNumber(0,str.length)];
            //将值添加到s中
            result += ch;
            //随机字体的大小
            let fontSize = randomNumber(30,40);
            //随机字符的旋转角度
            let angle = randomNumber(-15,15);
            //给画笔设置属性
            print.font = fontSize +'px Simhei';
            print.textBaseline = 'top';
            //设置字体的填充颜色
            print.fillStyle = randomColor(100,120);
            print.save();
            print.translate(35*i+10,5);
            print.rotate(angle*Math.PI/180);
            print.fillText(ch,0,0);
            print.restore();
        }

        //随机生成干扰线
        for(let i = 0; i < 5; i++){
            print.beginPath();
            print.moveTo(randomNumber(0,width),randomNumber(0,height));
            print.lineTo(randomNumber(0,width),randomNumber(0,height));
            print.strokeStyle = randomColor(180,230);
            print.lineWidth = 3;
            print.closePath();
            print.stroke();
        }

        //随机生成10个干扰点
        for(let i = 0; i < 10; i++){
            print.beginPath();
            print.arc(randomNumber(0,width),randomNumber(0,height),5,0,2*Math.PI);
            print.closePath();
            print.fillStyle = randomColor(150,200);
            print.fill();
        }

        return result;
      }
      
    },
    mounted(){
      this.yzm = this.captcha('#canvas',150,40);
    }
  }
</script>


<style lang="less" scoped>
  .container{
      height: 100vh;
      background-image: url(../assets/backgroud.png);
      background-repeat: no-repeat;
      background-position: center;

      display: flex;
      justify-content: center;
      align-items: center;
    .login-weaper{
      width: 70%;
      height: 500px;
      position: relative;
      min-height: 500px;
      box-shadow: -4px 5px 10px rgb(0 0 0 / 40%);
      display: flex;

      .login-left{
        height: 100%;
        width: 50%;
        background-color: rgba(255, 255, 255, 0.1490196078);
        background-size: 100% 100%;
        .title {
            font-weight: 600;
            color: #fff;
            text-shadow: 3px 3px 3px rgb(5 5 5 / 50%);
            background-image: url(../assets/login-border.png);
            background-size: 100% 100%;
            padding: 30px 30px;
            font-size: 34px;
            text-align: center;
            margin: 50px;
            margin-top: 180px;
        }
      }
      .login-right{
        height: 100%;
        width: 50%;
        background-color: #fff;
        display: flex;
        justify-content: center;
        align-items: center;

        .el-form{
            width: 65%;
            height: 65%;
            background-color: #fff;

            .title-right{
              font-size: 30px;
              font-weight: 500px;
              color: rgb(0, 0, 0);
              margin-bottom: 20px;
            }

            #canvas:hover{
              cursor: pointer;
            }
        
          }
          .el-button{
            width: 100%;
          }
          i{
            cursor: pointer;
            padding-right: 5px;
          }
      }
    }
  }
</style>
